package com.hy.storage.controller;

import com.hy.storage.service.StorageService;
import com.hy.storage.service.StorageServiceSaga;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class StorageController {
    @Autowired
    private StorageService storageService;
    @Autowired
    StorageServiceSaga storageServiceSaga;


    @GetMapping("storage/change")
    public String changeStorage(long productId , int used)  {
        return storageService.updateUsed(productId , used);
    }
    // http://localhost:8100/storage/tcc/change?productId=1&sold=2
    @GetMapping("storage/tcc/change")
    public boolean changeTccStorage(long productId , int sold)  {
        return storageService.reduceStock(productId , sold);
    }

        // http://localhost:8100/storage/xa/change?productId=1&sold=2
    @GetMapping("storage/xa/change")
    public boolean changeXaStorage(long productId , int sold)  {
        return storageService.reduceStockByXA(productId , sold);
    }


    /**
     * 库存扣减
     *
     * @param businessKey   businessKey
     * @param productId productId
     * @param sold         sold
     * @return
     */
    @RequestMapping(value = "/storageDeduct")
    boolean storageDeduct(@RequestParam("businessKey") String businessKey,
                          @RequestParam("productId") Integer productId,
                          @RequestParam("sold") Integer sold,
                          @RequestParam("storageException") String storageException) {
        log.info("库存扣减请求开始，业务id{},商品Id{}，扣减数量{}", businessKey, productId, sold);
        boolean result = storageServiceSaga.reduceStockBySaga(businessKey,storageException, productId, sold);
        log.info("库存扣减请求结束，业务id{},商品Id{}，扣减结果{}", businessKey, productId, result);
        return true;
    }

    /**
     * 库存补偿
     *
     * @param businessKey   businessKey
     * @param productId productId
     * @param sold         sold
     * @return
     */
    @RequestMapping(value = "/storageCompensate")
    boolean storageCompensate(@RequestParam("businessKey") String businessKey,
                              @RequestParam("productId") Integer productId,
                              @RequestParam("sold") Integer sold) {
        log.info("库存补偿请求开始，业务id{},商品Id{}，扣减数量{}", businessKey, productId, sold);
        boolean result = storageServiceSaga.storageCompensate(businessKey, productId, sold);
        log.info("库存补偿请求结束，业务id{},商品Id{}，扣减数量{}", businessKey, productId, result);
        return true;
    }

}
